"""
数据库操作管理工具
"""
import pymysql
from dbutils.pooled_db import PooledDB
from config.settings import DB_CONFIG
from core.logger import root_logger


class MysqlManager:
    def __init__(self, database: str = None):
        if database is not None:
            DB_CONFIG.update({"database": database})
        # 创建连接池
        self.pool = PooledDB(
            creator=pymysql,
            maxconnections=6,
            mincached=2,
            maxcached=5,
            maxshared=3,
            blocking=True,
            maxusage=None,
            setsession=[],
            ping=0,
            **DB_CONFIG
        )

    def fetch_data(self, sql, *args):
        conn = self.pool.connection()
        try:
            with conn.cursor() as cursor:
                cursor.execute(sql, *args)
                result = cursor.fetchall()
                return result
        except Exception as e:
            root_logger.error(f"Execute sql error! because: {e}. sql:{sql}\n")
        finally:
            conn.close()

        # 执行SQL语句并返回受影响的行数

    def execute_sql(self, sql, *args):
        conn = self.pool.connection()
        try:
            with conn.cursor() as cursor:
                affected_rows = cursor.execute(sql, *args)
                conn.commit()  # 提交事务
                return affected_rows
        except Exception as e:
            root_logger.error(f"Execute sql error! because: {e}. sql:{sql}\n")
        finally:
            conn.close()

        # 执行SQL查询并获取第一条数据

    def fetch_one(self, sql, *args):
        conn = self.pool.connection()
        try:
            with conn.cursor() as cursor:
                cursor.execute(sql, *args)
                result = cursor.fetchone()
                return result
        except Exception as e:
            root_logger.error(f"Execute sql error! because: {e}. sql:{sql}\n")
        finally:
            conn.close()
